package com.chwn.curiousdiary.ui.play.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.chwn.curiousdiary.DiaryApplication;
import com.chwn.curiousdiary.R;
import com.chwn.curiousdiary.api.IHomeApi;
import com.chwn.curiousdiary.api.IUserApi;
import com.chwn.curiousdiary.api.NetWork;
import com.chwn.curiousdiary.bean.StoryBean;
import com.chwn.curiousdiary.download.DownHelper;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.gloable.CustomEvent;
import com.chwn.curiousdiary.gloable.UserUtils;
import com.chwn.curiousdiary.service.AudioService;
import com.chwn.curiousdiary.service.IAudioService;
import com.chwn.curiousdiary.ui.play.fragment.PlayQueueFragment;
import com.chwn.curiousdiary.ui.play.fragment.TimingFragment;
import com.chwn.curiousdiary.utils.DialogUtil;
import com.chwn.curiousdiary.utils.ImgLoadUtil;
import com.chwn.curiousdiary.utils.PopupWindowUtils;
import com.chwn.curiousdiary.utils.StringUtils;
import com.chwn.curiousdiary.widget.HoloCircularProgressBar;
import com.chwn.curiousdiary.widget.PlaySeekBar;
import com.chwn.harulib.mvp.rx.HttpResult;
import com.chwn.harulib.util.ScreenUtil;
import com.chwn.harulib.util.ToastUtil;
import com.gyf.barlibrary.ImmersionBar;
import com.orhanobut.logger.Logger;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMusic;

import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by Myshikin on 2017/3/23.
 */
public class StoryPlayActivity extends AppCompatActivity {

    @BindView(R.id.toolbar)
    Toolbar                 mToolBar;
    @BindView(R.id.iv_background)
    ImageView               mBackGround;
    @BindView(R.id.iv_story_img)
    ImageView               mStoryImg;
    @BindView(R.id.tv_story_name)
    TextView                mStoryName;
    @BindView(R.id.sb_play_progress)
    SeekBar                 mPlayProgress;
    @BindView(R.id.play_seek)
    PlaySeekBar             mPlaySeek;
    @BindView(R.id.tv_play_time)
    TextView                mPlayTime;
    @BindView(R.id.tv_total_time)
    TextView                mTotalTime;
    @BindView(R.id.iv_play_pre)
    ImageView               mPlayPre;
    @BindView(R.id.iv_play_next)
    ImageView               mPlayNext;
    @BindView(R.id.iv_play_state)
    ImageView               mPlayState;
    @BindView(R.id.tv_play_title)
    TextView                mPlayTitle;
    @BindView(R.id.ll_bottom)
    LinearLayout            mLLBottom;
    @BindView(R.id.tv_praise_count)
    TextView                mPraiseTV;
    @BindView(R.id.iv_collection)
    ImageView               mCollectionIV;
    @BindView(R.id.iv_timming)
    ImageView               mTimmingIV;
    @BindView(R.id.iv_download)
    ImageView               mDownloadIV;
    @BindView(R.id.iv_praise)
    ImageView               mPraiseIV;
    @BindView(R.id.iv_play_mode)
    ImageView               mPlayModeIV;
    @BindView(R.id.iv_download_state)
    ImageView               mDownLoadState;
    @BindView(R.id.image_progress)
    HoloCircularProgressBar mImageProgress;
    @BindView(R.id.progress_play)
    ProgressBar             progressPlay;
    private AudioServiceConnection audioServiceConnection;
    private AudioService           mService;
    private AudioBroadcastReceiver audioBroadcastReceiver;

    private static final int MSG_UPDATE_PLAY_TIME = 0;


    /**
     * 分享内容
     */
    String content = "好奇日记";
    private StoryBean currentPlayStory;
    private int       mCurrentMaxTime;
    private String    userToken;
    private int       bgType;

    private int[] bgIds = new int[]{R.drawable.bg_play_adventure, R.drawable.bg_play_build, R.drawable.bg_play_fancy
            , R.drawable.bg_play_life, R.drawable.bg_play_china, R.drawable.bg_play_animal, R.drawable.bg_play_adventure,};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_story_play);
        ButterKnife.bind(this);

        ImmersionBar.with(this)
                .statusBarView(R.id.top_view)
                .statusBarAlpha(0.0f)
                .titleBar(mToolBar, true)
                .init();

        userToken = DiaryApplication.mInstance.getUserToken();
        initData();
        initView();
    }


    protected void initData() {

        Intent intent = new Intent(getIntent());
        intent.setClass(this, AudioService.class);
        startService(intent);

        audioServiceConnection = new AudioServiceConnection();
        bindService(intent, audioServiceConnection, BIND_AUTO_CREATE);

        IntentFilter filter = new IntentFilter();
        filter.addAction(AudioService.ACTION_PREPARED);
        audioBroadcastReceiver = new AudioBroadcastReceiver();
        registerReceiver(audioBroadcastReceiver, filter);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        bgType = getIntent().getIntExtra("bg_type", 0);

    }

    /**
     * 暂时取消播放错误回调处理
     * @param event
     */
    public void onEventMainThread(CustomEvent event) {
        switch (event.getState()) {
            case CustomEvent.STORY_PLAY_ERROR:
                ToastUtil.shortShowToast("播放失败，请检查网络连接");
                mHandler.removeCallbacksAndMessages(null);
                mPlayTime.setText("00:00");
                mTotalTime.setText("00:00");
                break;
            case CustomEvent.PLAY_STORY_DATA:
                mPlayTime.setText("00:00");
                mTotalTime.setText("00:00");
                mPlaySeek.setProgress(0);
                mPlayTitle.setText(Html.fromHtml("正在播放 " + "<font size = 16 >" + event.getTitle() + "</font>"));
                //设置音乐的标题
                StoryBean audioBean = (StoryBean) event.getMessage();
                mStoryName.setText(audioBean.getStoryTitle());
                ImgLoadUtil.displayCircle(mStoryImg, audioBean.getStoryImage());
                if (!TextUtils.isEmpty(audioBean.getTypeId())) {
                    bgType = getType(audioBean.getTypeId());
                    upDateBGImg();
                }
                //初始化点赞、收藏的状态显示 和 点赞数量的显示
                updateUserAbout(audioBean);
                updateTimmingState();
                break;
            case CustomEvent.TIMMING_START:
            case CustomEvent.TIMMING_STOP:
                updateTimmingState();
                break;
        }
    }


    protected void initView() {
        mPlaySeek.setOnSeekBarChangeListener(new AudioSeekBarChangeListener());
        upDateBGImg();
    }

    private void upDateBGImg() {
        if (bgType > bgIds.length || bgType == bgIds.length) {
            bgType = bgIds.length - 1;
        }
        mBackGround.setBackgroundResource(bgIds[bgType]);
    }

    private void playNext() {
        mService.playNext();
    }

    /**
     * 播放上一曲
     */
    private void playPre() {
        mService.playPre();
    }

    /**
     * 播放、暂停音乐
     */
    private void switchPlayPause() {
        mService.switchPlayPause();
        updatePlayPuseStatus();
    }

    /**
     * 切换播放模式
     */
    private void switchPlayMode() {
        mService.switchPlayMode();
        updatePlayModeStatus();
    }

    private void updateTimmingState() {
        mTimmingIV.setImageResource(mService.getTimmingPosition() == 0 ? R.drawable.icon_not_timming : R.drawable.icon_timming);
    }

    /**
     * 更新播放、暂停的背景图片
     */
    private void updatePlayPuseStatus() {
        if (mService == null) {
            return;
        }
        if (mService.isPlaying()) {
            progressPlay.setIndeterminateDrawable(getResources().getDrawable(R.drawable.progress_playing));
            progressPlay.setProgressDrawable(getResources().getDrawable(
                    R.drawable.progress_playing));
            mPlayState.setImageResource(R.drawable.icon_play_stop);
        } else {
            progressPlay.setIndeterminateDrawable(getResources().getDrawable(R.drawable.icon_scanner));
            progressPlay.setProgressDrawable(getResources().getDrawable(
                    R.drawable.icon_scanner));
            mPlayState.setImageResource(R.drawable.icon_play_start);
        }
    }

    /**
     * 更新播放模式的背景图片
     */
    private void updatePlayModeStatus() {
        switch (mService.getPlayMode()) {
            case AudioService.PLAY_MODE_REPATE_ALL:
                mPlayModeIV.setImageResource(R.drawable.play_icn_loop_prs);
                break;
            case AudioService.PLAY_MODE_RANDOM:
                mPlayModeIV.setImageResource(R.drawable.play_icn_shuffle);
                break;
            case AudioService.PLAY_MODE_REPATE_SINGLE:
                mPlayModeIV.setImageResource(R.drawable.play_icn_one_prs);
                break;
            default:
                break;
        }
    }

    @OnClick({R.id.iv_play_pre, R.id.iv_play_next, R.id.iv_play_state,
            R.id.ib_back, R.id.ib_share, R.id.iv_play_queue, R.id.iv_timming,
            R.id.iv_collection, R.id.iv_download, R.id.iv_praise, R.id.iv_play_mode})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_play_pre:
                if (isPlayerPrepared()) {
                    mHandler.removeCallbacksAndMessages(null);
                    playPre();
                }
                break;
            case R.id.iv_play_next:
                if (isPlayerPrepared()) {
                    mHandler.removeCallbacksAndMessages(null);
                    playNext();
                }
                break;
            case R.id.iv_play_state:
                if (isPlayerPrepared()) {
                    switchPlayPause();
                }
                break;
            case R.id.ib_back:
                finish();
                break;
            case R.id.ib_share:
                //                share();
                shareTwo();
                break;
            case R.id.iv_play_queue:

                PlayQueueFragment playQueueFragment = new PlayQueueFragment();
                Bundle extras = new Bundle();
                extras.putSerializable("list", mService.getmAudioList());
                extras.putInt("position", mService.getCurrentPlayPosition());
                extras.putInt("bgType", bgType);
                playQueueFragment.setArguments(extras);
                playQueueFragment.show(getSupportFragmentManager(), "playlistframent");
                break;
            case R.id.iv_timming:

                TimingFragment timmingFragment = new TimingFragment();
                Bundle extrasTimming = new Bundle();
                extrasTimming.putInt("bgType", bgType);
                extrasTimming.putInt("position", mService.getTimmingPosition());
                timmingFragment.setArguments(extrasTimming);
                timmingFragment.show(getSupportFragmentManager(), "timingframent");
                break;
            case R.id.iv_collection:
                collection();
                break;
            case R.id.iv_download:
                download();
                break;
            case R.id.iv_praise:
                praise();
                break;
            case R.id.iv_play_mode:
                switchPlayMode();
                break;
        }
    }

    /**
     * 下载
     */
    private void download() {
        if (checkData())
            return;

        NetWork.getInstance().getApiService(IUserApi.class)
                .downloadStory(storyId, userToken, Constant.OSTYPE)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<HttpResult<Object>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(HttpResult<Object> objectHttpResult) {
                    }
                });
        if (downState == 0) {
            StoryBean currentPlayStory = mService.getCurrentPlayStory();
            DownHelper.downStory(this, currentPlayStory);
            downState = 1;
            mDownloadIV.setImageResource(R.drawable.icon_downloaded);
        } else {
            ToastUtil.shortShowToast("已经下载了");
        }
    }

    int    praiseState;
    int    collectionState;
    int    praiseCount;
    int    downState;
    String storyId;

    /**
     * 收藏
     */
    private void collection() {

        if (checkData())
            return;
        NetWork.getInstance().getApiService(IUserApi.class)
                .collectionStory(storyId, userToken, Constant.OSTYPE, collectionState == 1 ? 0 : 1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<HttpResult<Object>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(getApplicationContext(), collectionState == 0 ? "收藏失败" : "取消收藏失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(HttpResult<Object> objectHttpResult) {
                        collectionState = collectionState == 1 ? 0 : 1;
                        Toast.makeText(getApplicationContext(), collectionState == 1 ? "收藏成功" : "取消收藏成功", Toast.LENGTH_SHORT).show();
                        updateCollectionState();

                        CustomEvent customEvent = new CustomEvent(CustomEvent.UPDATE_COLLECT, collectionState);
                        customEvent.setMessage(storyId);
                        EventBus.getDefault().post(customEvent);
                    }
                });
    }

    /**
     * 点赞
     */
    private void praise() {
        if (checkData())
            return;
        NetWork.getInstance().getApiService(IUserApi.class)
                .praiseStory(storyId, userToken, Constant.OSTYPE, praiseState == 1 ? 0 : 1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<HttpResult<Object>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(getApplicationContext(), praiseState == 0 ? "点赞失败" : "取消点赞失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(HttpResult<Object> objectHttpResult) {
                        if (praiseState == 1) {
                            praiseCount--;
                        } else {
                            praiseCount++;
                        }
                        praiseState = praiseState == 1 ? 0 : 1;
                        Toast.makeText(getApplicationContext(), praiseState == 1 ? "点赞成功" : "取消点赞成功", Toast.LENGTH_SHORT).show();
                        updatePraiseState();
                        updatePraiseCount();
                    }
                });
    }

    private boolean checkData() {
        if (TextUtils.isEmpty(storyId)) {
            return true;
        }

        if (!UserUtils.isLogin(this)) {
            return true;
        }
        return false;
    }

    private boolean isPlayerPrepared() {
        if (!"缓冲中...".equals(mPlayTitle.getText().toString())) {
            return true;
        }
        return false;
    }

    /**
     * activity和AudioService连接通道
     */
    private class AudioServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            IAudioService music = (IAudioService) service;
            mService = music.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //        netWork();
    }

   /* private void netWork() {
        if (!NetworkUtils.isAvailable(this)) {
            Toast.makeText(this, getString(com.shuyu.gsyvideoplayer.R.string.no_net), Toast.LENGTH_LONG).show();
            return;
        }
    }*/


    /**
     * 音乐准备完成的接收者
     */
    private class AudioBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {


            //设置音乐的进度最大值
            if (mService != null && mService.getMaxTime() != 0) {
                mCurrentMaxTime = mService.getMaxTime();
            }
            mPlaySeek.setMax(mCurrentMaxTime);

            //更新播放、暂停按钮
            updatePlayPuseStatus();

            //开始更新已播放时间、总时间
            startPlayTotalTime();

            //更新播放模式的背景图片
            updatePlayModeStatus();

            updateTimmingState();


            //            String play_position = intent.getStringExtra("play_position");
            //            mPlayTitle.setText(Html.fromHtml("正在播放 " + "<font size = 16 >" + play_position + "</font>"));
            //
            //            //设置音乐的标题
            //            StoryBean audioBean = (StoryBean) intent.getSerializableExtra("bean");
            //            mStoryName.setText(audioBean.getStoryTitle());
            //            ImgLoadUtil.displayCircle(mStoryImg, audioBean.getStoryImage());
            //            if (!TextUtils.isEmpty(audioBean.getTypeId())) {
            //                bgType = getType(audioBean.getTypeId());
            //                upDateBGImg();
            //            }
            //            //初始化点赞、收藏的状态显示 和 点赞数量的显示
            //            updateUserAbout(audioBean);
        }
    }

    private String[] storyID = new String[]{"dc4c8cf1075c461aac0322db7afb8042", "c3aa6b542c564a779c9f2bce235f893a", "4c86caf64c38426c9f45fcb74b592f1f"
            , "def98e39eeea4cc38bbcae03ea4f1160", "0ec9cab1cb6442e98689a7d6c4265f29", "f4aefe3d45ab446eaab2807d241e7d8c", "-1"};

    private int getType(String typeId) {
        return Arrays.asList(storyID).indexOf(typeId);
    }

    /**
     * 初始化点赞、收藏的状态显示 和 点赞数量的显示
     */
    private void updateUserAbout(StoryBean audioBean) {
        storyId = audioBean.getStoryId();

        NetWork.getInstance()
                .getHomeApi()
                .getStoryDetail(storyId, userToken, Constant.OSTYPE)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<HttpResult<List<StoryBean>>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        updatePraiseState();
                        updateCollectionState();
                        updatePraiseCount();
                    }

                    @Override
                    public void onNext(HttpResult<List<StoryBean>> listHttpResult) {
                        StoryBean storyBean = listHttpResult.getResdata().get(0);
                        praiseState = storyBean.getStoryPraiseState();
                        collectionState = storyBean.getStroyCollectionState();
                        praiseCount = storyBean.getStroyPraiseCount();
                        updatePraiseState();
                        updateCollectionState();
                        updatePraiseCount();
                    }
                });

        updateDownState();
    }

    private void updateDownState() {
        downState = DownHelper.isDown(this, storyId) ? 1 : 0;
        mDownloadIV.setImageResource(downState == 1 ? R.drawable.icon_downloaded : R.drawable.icon_download_story);
    }

    /**
     * 更新点赞数量的显示
     */
    private void updatePraiseCount() {
        if (praiseCount == 0 || praiseCount < 0) {
            mPraiseTV.setVisibility(View.GONE);
        } else {
            mPraiseTV.setVisibility(View.VISIBLE);
            mPraiseTV.setText(praiseCount + "");
        }
    }

    /**
     * 更新收藏的状态显示
     */
    private void updateCollectionState() {
        mCollectionIV.setImageResource(collectionState == 1 ? R.drawable.icon_collected : R.drawable.icon_not_collection);
    }

    /**
     * 更新点赞的状态显示
     */
    private void updatePraiseState() {
        mPraiseIV.setImageResource(praiseState == 1 ? R.drawable.icon_praised_story : R.drawable.icon_praise_story);
    }

    /**
     * 开始更新已播放、总时间
     */
    private void startPlayTotalTime() {
        if (mService == null) {
            return;
        }

        int currentTime = mService.getCurrentTime();
        updatePlayTime(currentTime);
        mHandler.sendEmptyMessageDelayed(MSG_UPDATE_PLAY_TIME, 500);
    }

    /**
     * 更新音乐的播放进度 、已播放时间
     */
    private void updatePlayTime(int currentTime) {
        String current = StringUtils.formatTime(currentTime);
        String total = StringUtils.formatTime(mCurrentMaxTime);
        mPlayTime.setText(current);
        mTotalTime.setText(total);
        //设置进度条的进度
        mPlaySeek.setProgress(currentTime);
        mImageProgress.setProgress(1.0f * currentTime / mCurrentMaxTime);
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_UPDATE_PLAY_TIME://已播放时间
                    startPlayTotalTime();
                    break;
                default:
                    break;
            }
        }
    };

    int mProgress;

    /**
     * 音乐播放进度的监听
     */
    private class AudioSeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                updatePlayTime(progress);
                mProgress = progress;
                mImageProgress.setProgress(1.0f * mProgress / mCurrentMaxTime);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mService.seekTo(mProgress);
            mImageProgress.setProgress(1.0f * mProgress / mCurrentMaxTime);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        DialogUtil.dismissWaitDialog();
    }


    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {
            DialogUtil.showWaitDialog(StoryPlayActivity.this, "", true);
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            DialogUtil.dismissWaitDialog();
            Toast.makeText(StoryPlayActivity.this, " 分享成功", Toast.LENGTH_SHORT).show();
            uploadShareInfo();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            DialogUtil.dismissWaitDialog();
            Toast.makeText(StoryPlayActivity.this, " 分享失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            DialogUtil.dismissWaitDialog();
        }
    };

    private void uploadShareInfo() {
        String userToken = DiaryApplication.mInstance.getUserToken();
        if (!TextUtils.isEmpty(userToken) && currentPlayStory != null) {
            NetWork.getInstance()
                    .getApiService(IHomeApi.class)
                    .shareStory(currentPlayStory.getStoryId(), userToken, 3)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<HttpResult<Object>>() {
                        @Override
                        public void call(HttpResult<Object> objectHttpResult) {
                            Logger.e(objectHttpResult.getErrorMessage());
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                        }
                    });
        }

    }

    /**
     * 分享途径: 1--QQ 2--QQ空间 3--微信 4--朋友圈
     */

   /* private void share() {
        currentPlayStory = mService.getCurrentPlayStory();
        final PopupWindowUtils popupWindowUtils = PopupWindowUtils.getInstance();
        popupWindowUtils.attachActivity(StoryPlayActivity.this, R.layout.pop_share, mLLBottom)
                .wiewSize(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
                .location(Gravity.BOTTOM, 0, ScreenUtil.getBottomStatusHeight(StoryPlayActivity.this))
                .focuseAble(true)
                .Animation(PopupWindowUtils.ANIMATION_BOTTOM)
                .setPopupWindowItemViewClickListener(new PopupWindowUtils.SetonPopWindowItemViewClickListenter() {
                    @Override
                    public void onPopWindowItemViewClickListener(int id) {
                        UMImage umImage = new UMImage(StoryPlayActivity.this, R.mipmap.ic_launcher);
                        UMImage storyImage = new UMImage(StoryPlayActivity.this, currentPlayStory.getStoryImage());

                        UMusic music = new UMusic(currentPlayStory.getStoryUrl());
                        music.setTitle(currentPlayStory.getStoryTitle());//音乐的标题
                        music.setThumb(storyImage);//音乐的缩略图
                        music.setDescription(currentPlayStory.getStoryDetailTitle());
                        switch (id) {
                            case R.id.iv_qq:
                                music.setmTargetUrl(currentPlayStory.getStroyShareURL());
                                new ShareAction(StoryPlayActivity.this)
                                        .setPlatform(SHARE_MEDIA.QQ)
                                        .withText(content)
                                        .withMedia(umImage)
                                        .withMedia(music)
                                        .setCallback(umShareListener)
                                        .share();
                                break;
                            case R.id.iv_qq_friend:
                                music.setmTargetUrl(currentPlayStory.getStroyShareURL());
                                new ShareAction(StoryPlayActivity.this)
                                        .setPlatform(SHARE_MEDIA.QZONE)
                                        .setCallback(umShareListener)
                                        .withText(content)
                                        .withMedia(umImage)
                                        .withMedia(music)
                                        .share();
                                break;
                            case R.id.iv_wechat:
                                music.setmTargetUrl(currentPlayStory.getStroyShareURL());
                                new ShareAction(StoryPlayActivity.this)
                                        .setPlatform(SHARE_MEDIA.WEIXIN)
                                        .setCallback(umShareListener)
                                        .withText(content)
                                        .withMedia(umImage)
                                        .withMedia(music)
                                        .share();
                                break;
                            case R.id.iv_wechat_friend:
                                music.setmTargetUrl(currentPlayStory.getStroyShareURL());
                                new ShareAction(StoryPlayActivity.this)
                                        .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                                        .setCallback(umShareListener)
                                        .withText(content)
                                        .withMedia(umImage)
                                        .withMedia(music)
                                        .share();

                                break;
                            case R.id.iv_share_close:
                                popupWindowUtils.dissMissPopWindow();
                                break;
                        }
                        popupWindowUtils.dissMissPopWindow();
                    }
                }, R.id.iv_qq, R.id.iv_qq_friend, R.id.iv_wechat, R.id.iv_wechat_friend, R.id.iv_share_close)
                .show();
    }*/

    private PopupWindow mPopWindow;

    void shareTwo() {
        currentPlayStory = mService.getCurrentPlayStory();
        View contentView = LayoutInflater.from(this).inflate(R.layout.layout_share, null);
        mPopWindow = new PopupWindow(contentView,
                RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.MATCH_PARENT, true);
        mPopWindow.setContentView(contentView);

        contentView.findViewById(R.id.iv_qq).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickShare(v);
            }
        });
        contentView.findViewById(R.id.iv_qq_friend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickShare(v);
            }
        });
        contentView.findViewById(R.id.iv_wechat).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickShare(v);
            }
        });
        contentView.findViewById(R.id.iv_wechat_friend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickShare(v);
            }
        });
        contentView.findViewById(R.id.iv_share_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickShare(v);
            }
        });

        mPopWindow.setOutsideTouchable(true);

        mPopWindow.setAnimationStyle(PopupWindowUtils.ANIMATION_BOTTOM);
        mPopWindow.showAtLocation(mLLBottom, Gravity.BOTTOM, 0, ScreenUtil.getBottomStatusHeight(StoryPlayActivity.this));

    }

    private void onClickShare(View v) {
        UMImage umImage = new UMImage(StoryPlayActivity.this, R.mipmap.ic_launcher);
        UMImage storyImage = new UMImage(StoryPlayActivity.this, currentPlayStory.getStoryImage());

        UMusic music = new UMusic(currentPlayStory.getStoryUrl());
        music.setTitle(currentPlayStory.getStoryTitle());//音乐的标题
        music.setThumb(storyImage);//音乐的缩略图
        music.setDescription(currentPlayStory.getStoryDetailTitle());
        switch (v.getId()) {
            case R.id.iv_qq:
                music.setmTargetUrl(currentPlayStory.getStroyShareURL());
                new ShareAction(StoryPlayActivity.this)
                        .setPlatform(SHARE_MEDIA.QQ)
                        .withText(content)
                        .withMedia(umImage)
                        .withMedia(music)
                        .setCallback(umShareListener)
                        .share();
                break;
            case R.id.iv_qq_friend:
                music.setmTargetUrl(currentPlayStory.getStroyShareURL());
                new ShareAction(StoryPlayActivity.this)
                        .setPlatform(SHARE_MEDIA.QZONE)
                        .setCallback(umShareListener)
                        .withText(content)
                        .withMedia(umImage)
                        .withMedia(music)
                        .share();
                break;
            case R.id.iv_wechat:
                music.setmTargetUrl(currentPlayStory.getStroyShareURL());
                new ShareAction(StoryPlayActivity.this)
                        .setPlatform(SHARE_MEDIA.WEIXIN)
                        .setCallback(umShareListener)
                        .withText(content)
                        .withMedia(umImage)
                        .withMedia(music)
                        .share();
                break;
            case R.id.iv_wechat_friend:
                music.setmTargetUrl(currentPlayStory.getStroyShareURL());
                new ShareAction(StoryPlayActivity.this)
                        .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(umShareListener)
                        .withText(content)
                        .withMedia(umImage)
                        .withMedia(music)
                        .share();

                break;
            case R.id.iv_share_close:
                mPopWindow.dismiss();
                break;
        }
        mPopWindow.dismiss();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //activity销毁前解绑服务
        unbindService(audioServiceConnection);
        unregisterReceiver(audioBroadcastReceiver);
        //移除所有的消息
        mHandler.removeCallbacksAndMessages(null);
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }

        ImmersionBar.with(this).destroy();
    }

}
